package com.wlf.server.common.service;

import cn.hutool.http.HttpUtil;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.wlf.server.common.config.FileConfig;
import com.wlf.server.common.context.BeanContext;
import com.wlf.server.common.entity.SysAttachment;
import com.wlf.server.common.service.iservice.FileUploadService;
import com.wlf.server.web.util.ServletUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
public class FileUploadServiceQiNiuImpl implements FileUploadService {
    @Resource
    FileConfig.QiNiuFileConfig qiNiuFileConfig;

    /**
     * 生成凭证
     *
     * @return 凭证
     */
    private String getUpToken() {
        Auth auth = Auth.create(qiNiuFileConfig.getAccessKey(), qiNiuFileConfig.getSecretKey());
        return auth.uploadToken(qiNiuFileConfig.getBucket());
    }

    private UploadManager getUploadManager() {
        Configuration cfg = new Configuration(Region.huanan());
        cfg.useHttpsDomains = false;
        return new UploadManager(cfg);
    }


    /**
     * 上传文件
     *
     * @param file   文件
     * @param remark 文件备注
     * @return 返回
     */
    @Override
    public SysAttachment plus(MultipartFile file, String remark) {
        SysAttachment attachment = initAttachment(file);
        attachment.setFileSrc(FileConfig.FileType.qiniu.name());
        try {
            Response response = getUploadManager().put(file.getInputStream()
                    .readAllBytes(), attachment.getId(), getUpToken());
            //解析上传成功的结果
            String s = response.bodyString();
            log.info("七牛云文件上传返回：{}", s);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                throw new RuntimeException(ex2);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        attachment.setWebPath(qiNiuFileConfig.getHost() + attachment.getId());
        attachment.setRemark(remark);
        return attachment;
    }


    /**
     * 删除文件
     *
     * @param id 文件Id
     */
    @Override
    public void del(String id) {
        Configuration cfg = new Configuration(Region.huanan());
        cfg.useHttpsDomains = false;
        Auth auth = Auth.create(qiNiuFileConfig.getAccessKey(), qiNiuFileConfig.getSecretKey());
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            bucketManager.delete(qiNiuFileConfig.getBucket(), id);
        } catch (QiniuException ex) {
            //如果遇到异常，说明删除失败
            log.warn("七牛云删除失败：{}", ex.code());
            log.warn(ex.response.toString());
        }
    }

    /**
     * 下载文件
     *
     * @param id 文件Id
     */
    @Override
    public void read(String id) {
        try {
            SysAttachment attachment = BeanContext.getBean(SysAttachmentService.class).getById(id);
            HttpServletResponse response = ServletUtil.getResponse();
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    ContentDisposition.attachment().filename(
                                    attachment.getOriginalFilename(), StandardCharsets.UTF_8)
                            .build().toString()
            );
            FileCopyUtils.copy(
                    HttpUtil.downloadBytes(qiNiuFileConfig.getHost()+id), response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("读取附件失败", e);
        }
    }
}
